let loadings = [];

class Messengers {
  constructor() {
    this.loadingInstance = null;
  }

  // 双向通信 有回调
  async on(key, data, callback) {
    let noLoading = ["convertFils"];
    if (window.electronAPI[key]) {
      console.log("on", key);
      if (noLoading.indexOf(key) === -1 && !loadings.length) {
      }
      try {
        let result = await window.electronAPI[key](data);

        if (this.loadingInstance && !loadings.length) {
          this.loadingInstance.close();
          this.loadingInstance = null;
        }
        if (callback) {
          callback(result);
        }
        return;
      } catch (e) {
        if (this.loadingInstance && !loadings.length) {
          this.loadingInstance.close();
          this.loadingInstance = null;
        }
         
      }

      if (callback) {
        callback(null);
      }
    }
  }

  // 单向通信
  send(key, data) {
    console.log("send", key);
    window.electronAPI.send(key, data);
  }

  $on(key, fn) {
    console.log("$on", key);
    window.electronAPI.on(key, fn);
  }
}

window.messengers = new Messengers();
